#include "BUCK_Handler.h"

uint8 u8BuckStatus;
extern stateMachine sChargerState;


void vfnBuck_ADC_Init (void)
{
    // Self explanatory
    vfnADC_DisableInterrupt ();
    
    // Single conversion mode as we have to switch between ADC channels
    vfnADC_SingleConv ();
    
    // ADC input clock is not divided
    vfnADC_ClockDivideSelect (ADC_CLK_DIVIDER_1);
    
    // ADC runs from bus clock
    vfnADC_UseBusClock ();
    
    // Use 10 bit resolution
    vfnADC_ResolutionSet10 ();
    
    // Lower power mode as speed is not crucial for the application
    vfnADC_LowPowerMode ();
    
    // Long sample time to improve accuracy
    vfnADC_SetSampleTime (ADC_LONG_SAMPLE_TIME);
    
    // Enable ADC function on pin that measures DC-DC Converter output voltage
    vfnADC_PinEnable (ADC_BUCK_OUTPUT_V);
    
    // Enable ADC function on pin that measures Solar Panel Voltage
    vfnADC_PinEnable (ADC_SOLAR_PANEL_CHAN);
    
    // Enable ADC function on pin that measures the MC34671's ISET pin
    vfnADC_PinEnable (ADC_MC34671_ISET);
    
    // Enable ADC function on pin that measures the battery voltage
    vfnADC_PinEnable (ADC_BATTERY_CHAN);   

}

void vfnBuck_PWM_Init (void)
{
	vfnTPM_SetModulo(100);   // Timer period is 10us

    // Set clock prescaler to 1
    vfnTPM_SetPrescalerDivisor(TPM_PRESCALER_1);
    
    // Select Bus as clock source
    vfnTPM_SelectClock (TPM_CLK_BUS);

    
    // Channel 0 configured as edge aligned PWM, high true pulses
    vfnTPM_ChannelEdgeAligned (BUCK_PWM_CHANNEL, TPM_HIGH_TRUE);
      
    // Initalize channel 0 pwm value at 0
    vfnTPM_SetChannelValue (BUCK_PWM_CHANNEL, 0);
     
    return;
}

void vfnBuck_IncreaseDutyCycle (void)
{
    // Calls the TPM driver to increase PWM D
    uint8 u8currentvalue;
    
    u8currentvalue = u8Buck_GetDutyCycle();
    
    u8currentvalue++;
    
    vfnTPM_SetChannelValue (BUCK_PWM_CHANNEL, u8currentvalue);
    
    return;        
}

void vfnBuck_DecreaseDutyCycle (void)
{
    // Calls the TPM driver to reduce PWM D
    uint8 u8currentvalue;
    
    u8currentvalue = u8Buck_GetDutyCycle();
    
    u8currentvalue--;
    
    vfnTPM_SetChannelValue (BUCK_PWM_CHANNEL, u8currentvalue);
    
    return;
}

uint8 u8Buck_GetDutyCycle (void)
{
    // Calls the TPM driver and returns the duty cycle 
    return (uint8)(u16TPM_CheckChannelValue(BUCK_PWM_CHANNEL));      
}

uint8 u8Buck_IsDutyCycleMax (void)
{
    if (u8Buck_GetDutyCycle() == 100)
    {
        return 1;
    }
    return 0;
}

uint16 u16Buck_GetOutputVoltage (void)
{
    vfnADC_ChannelSelect(ADC_BUCK_OUTPUT_V); // Select appropiate ADC channel
    
    while(!u8ADC_CCFCheck());  // Wait until conversion is complete
    
    return u16ADC_GetResult();
}

uint8 u8Buck_IsOutputLow (void)
{
    // If buck output voltage is under preset limit, return 1, otherwise 0
    
    if (u16Buck_GetOutputVoltage() < BUCK_OUTPUT_VOLTAGE_LOW)
    {
        return 1;
    }
    return 0;
}

uint8 u8Buck_IsOutputHigh (void)
{
    // If buck output voltage is over preset limit, return 1, otherwise 0
    
    if (u16Buck_GetOutputVoltage() > BUCK_OUTPUT_VOLTAGE_HIGH)
    {
        return 1;
    }
    return 0;
}

void vfnBuck_TurnOff (void)
{
    u8BuckStatus = OFF;
    vfnTPM_SetChannelValue (BUCK_PWM_CHANNEL, 0);    
}

void vfnBuck_TurnOn (void)
{
    u8BuckStatus = ON;
    vfnTPM_SetChannelValue (BUCK_PWM_CHANNEL, 1);
}

void vfnBuck_RegulateVoltage (void)
{
    if (u8Buck_IsOutputLow())
    {
        // If buck output is lower than preset low limit, check to see if
        // pwm duty cycle should be increased or charge current reduced
        
        if (u8Buck_IsDutyCycleMax())    // if duty cycle is at 100%, then try
        {                               // to reduce charge current
            if (u8MC34671_IsMinISET())
            {
                /* QUITAR ESTE PUTO COMENTARIO */
               
                  
                vfnBuck_TurnOff();
                MC34671_EN = MC34671_DISABLE;
                
                sChargerState.u8prev2State = sChargerState.u8prevState;
                sChargerState.u8prevState = sChargerState.u8currentState;
                sChargerState.u8currentState = WAIT_FOR_SUN1;
                
                
                // Ya chupaste faros, rutina de apagado pq no hay luz
                // cambia el estado de la makina de estados de la carga
                // a modo wait for the sun y tomate unos tragos en lo que sale :D
                /* QUITAR ESTE PUTO COMENTARIO */
            }
            else                            // if charge current is not yet at
            {                               // the lowest possible value, then 
                vfnMC34671_DecreaseISET();  // decrease it to the next step
            }
        }
        else                            // if duty cycle is < 100%, then just
        {                               // increase duty cycle
            vfnBuck_IncreaseDutyCycle();
        }
    }
    else if (u8Buck_IsOutputHigh())
    {
        // If buck output is higher than preset limit, check to see if
        // pwm duty cycle should be reduced or charge current increased
        
 		if (u8Buck_GetDutyCycle() < BUCK_PWM_LIMIT)
        {
            if (!u8MC34671_IsMaxISET())     // If Charge current is not max,
            {                               // increase it
                vfnMC34671_IncreaseISET();
            }
            else                            // if it is max, then just
            {                               // decrease the converter duty cycle
                vfnBuck_DecreaseDutyCycle();
            }
        }
        else
        {
        	vfnBuck_DecreaseDutyCycle();
        }
    }
    else    // If voltage output is within range, then do nothing
    {
        return;
    }
}


/*
void vfnBuck_RegulateVoltage (void)
{
    if (u8Buck_IsOutputLow())
    {
        // If buck output is lower than preset low limit, check to see if
        // pwm duty cycle should be increased or charge current reduced
        
        if (!u8Buck_IsDutyCycleMax())                     
        {                               // increase duty cycle
            vfnBuck_IncreaseDutyCycle();
        }
    }
    else if (u8Buck_IsOutputHigh())
    {
        // If buck output is higher than preset limit, check to see if
        // pwm duty cycle should be reduced or charge current increased
        
        if (u8Buck_GetDutyCycle() > 0)                              
        {
            vfnBuck_DecreaseDutyCycle();  // decrease the converter duty cycle
        }

    }
    else    // If voltage output is within range, then do nothing
    {
        return;
    }
}
*/









